/*
Illuminator (LED drawing tool for iPhone)
Copyright (C) 2008
Nik S Denin
Ivan A Vlasov
Dmitriy A Jackovlev

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

/* USAGE:
[TwitPicAPI uploadAndPostWithFile:@"/tmp/i.png" withUsername:@"twitterUsername" withPassword:@"twitterPassword" withMessage:@"twitterStatusMessage"];

Returns @"ok" if there was no error
or string (if error):
@"Error code:<number_of_error>\nMessage:<cause_of_error>"
*/

#import <OfficeImport/NSXMLDocument.h>
#import <OfficeImport/NSXMLElement.h>

#import "TwitPicAPI.h"

@implementation TwitPicAPI

+ (NSString*)uploadAndPostWithFile:(NSString*)filename withUsername:(NSString *)username withPassword:(NSString *)password withMessage:(NSString *)message
{
	NSMutableURLRequest *twitRequest = [NSMutableURLRequest requestWithURL:TWITPIC_UPLOADANDPOST_URL];
	[twitRequest setHTTPMethod:@"POST"];
	[twitRequest addValue:TWITPIC_CONTENTTYPE forHTTPHeaderField: @"Content-Type"];
	NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
	[params setObject:username forKey:@"username"];
	[params setObject:password forKey:@"password"];
	[params setObject:message forKey:@"message"];
  	[params setObject:[NSData dataWithContentsOfFile:filename] forKey:@"media"];
	[twitRequest setHTTPBody:[self POSTHelper:params]];
	NSURLResponse *twitResponse = nil;
	NSError *twitError = nil;
	NSData *twitResponseData = nil;
	twitResponseData = [NSURLConnection sendSynchronousRequest:twitRequest returningResponse:&twitResponse error:&twitError];
	NSXMLDocument *xmlResponce = [[NSXMLDocument alloc] initWithXMLString:[[NSString alloc] initWithData:twitResponseData encoding:NSUTF8StringEncoding] options:0 error:&twitError];
	if ( ![[[[xmlResponce rootElement] attributeForName:@"status"] stringValue] isEqualToString:@"ok"] )
	{
		return [NSString stringWithFormat:@"Error code:%@\nMessage:%@",[[[[xmlResponce rootElement] childAtIndex:0] attributeForName:@"code"] stringValue],[[[[xmlResponce rootElement] childAtIndex:0] attributeForName:@"msg"] stringValue]];
	}
	return @"ok";
}

+ (NSString *)uploadWithData:(NSString*)filename withUsername:(NSString *)username withPassword:(NSString *)password
{
	NSMutableURLRequest *twitRequest = [NSMutableURLRequest requestWithURL:TWITPIC_UPLOAD_URL];
	[twitRequest setHTTPMethod:@"POST"];
	[twitRequest addValue:TWITPIC_CONTENTTYPE forHTTPHeaderField: @"Content-Type"];
	NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
	[params setObject:username forKey:@"username"];
	[params setObject:password forKey:@"password"];
	[params setObject:[NSData dataWithContentsOfFile:filename] forKey:@"media"];
	[twitRequest setHTTPBody:[self POSTHelper:params]];
	NSURLResponse *twitResponse = nil;
	NSError *twitError = nil;
	NSData *twitResponseData = nil;
	twitResponseData = [NSURLConnection sendSynchronousRequest:twitRequest returningResponse:&twitResponse error:&twitError];
	NSXMLDocument *xmlResponce = [[NSXMLDocument alloc] initWithXMLString:[[NSString alloc] initWithData:twitResponseData encoding:NSUTF8StringEncoding] options:0 error:&twitError];
	if ( ![[[[xmlResponce rootElement] attributeForName:@"status"] stringValue] isEqualToString:@"ok"] )
	{
		return [NSString stringWithFormat:@"Error code:%@\nMessage:%@",[[[[xmlResponce rootElement] childAtIndex:0] attributeForName:@"code"] stringValue],[[[[xmlResponce rootElement] childAtIndex:0] attributeForName:@"msg"] stringValue]];
	}
	return @"ok";
}

+ (NSData *)POSTHelper:(NSDictionary *) paramsDict
{
	NSMutableData *postBody = [[NSMutableData alloc] init];
	NSEnumerator *enumerator = [paramsDict keyEnumerator];
	NSString *key;
	[postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
	while ( (key = [enumerator nextObject]) != nil)
	{
		if (![key isEqualToString:@"media"])
			[postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\nContent-Disposition: form-data; name=\"%@\"\r\n\r\n%@", TWITPIC_BOUNDARY, key, [paramsDict objectForKey:key]] dataUsingEncoding:NSUTF8StringEncoding]];
		if ([key isEqualToString:@"media"]);
			
	}
	if ([paramsDict objectForKey:@"media"])
	{
		[postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\nContent-Disposition: form-data; name=\"media\"; filename=\"illuminator\"\r\nContent-Type: image/png\r\n\r\n", TWITPIC_BOUNDARY] dataUsingEncoding:NSUTF8StringEncoding]];
		[postBody appendData:[paramsDict objectForKey:@"media"]];
	}
	[postBody appendData:[@"\r\n-------------------------------41184676334--\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
	TRACE(@"POST Body: %@",[[NSString alloc] initWithData:postBody encoding:NSASCIIStringEncoding]);
	return [postBody retain];
}
@end // TwitPicAPI
